package com.kuang.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {


    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置druid监控管理后台的servlet
     * SpringBoot内置servlet容器没有web.xml文件 替代方式:ServletRegistrationBean
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean servletBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");


        Map<String, String> initParameters = new HashMap<String, String>();

        //后台需要有人登录 用户名和密码 loginUsername和loginPassword是固定的
        initParameters.put("loginUsername", "admin");
        initParameters.put("loginPassword", "123456");

        //后台允许谁可以访问  为空值的时候表示都可以访问
        //只允许本机访问:initParameters.put("allow","localhost");
        initParameters.put("allow", "");

        //IP为192.168.1.20的不允许访问
        initParameters.put("kuangshen", "192.168.1.20");

        servletBean.setInitParameters(initParameters);
        return servletBean;
    }

    /**
     * 配置druid监控之web监控filter
     * webStatFilter：用于配置web和druid数据源之间的管理关联监控统计
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean filterBean = new FilterRegistrationBean();

        filterBean.setFilter(new WebStatFilter());
        Map<String, String> initParameters = new HashMap<String, String>();

        //exclusions：设置哪些请求进行过滤排除
        initParameters.put("exclusions", ".js,.css,/druid/*,/jdbc/*");

        // "/*" 表示过滤所有请求
        filterBean.setUrlPatterns(Arrays.asList("/*"));

        filterBean.setInitParameters(initParameters);

        return filterBean;
    }

}
